package com.zmn.oms.third.jddj;

import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.common.utils.HttpUtil;
import com.zmn.oms.third.jddj.dto.JddjRequestDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 京东到家渠道工具类
 *
 * @author xiewenbing
 * @date 2021/01/18
 */
@Slf4j
public class JddjUtil {

    /**
     * 生成http post 请求数据
     *
     * @param requestDTO
     * @return
     */
    public static Map<String,String> getRequestParam(JddjRequestDTO requestDTO) {

        Map<String,String> params = new HashMap<>(7);

        params.put("app_key",requestDTO.getApp_key());
        params.put("format",requestDTO.getFormat());
        params.put("jd_param_json",requestDTO.getJd_param_json());
        params.put("sign",requestDTO.getSign());
        params.put("timestamp",requestDTO.getTimestamp());
        params.put("token",requestDTO.getToken());
        params.put("v",requestDTO.getV());

        return params;
    }

    /**
     * 生成签名
     *
     * @param requestDTO
     * @return
     */
    public static String makeSign(JddjRequestDTO requestDTO) {

        if (Objects.isNull(requestDTO)) {
            return "";
        }

        StringBuilder sbSignContent = new StringBuilder();
        sbSignContent.append(JddjConsts.APP_SECRET).append("app_key").append(requestDTO.getApp_key()).
                append("format").append(requestDTO.getFormat()).
                append("jd_param_json").append(requestDTO.getJd_param_json()).
                append("timestamp").append(requestDTO.getTimestamp()).
                append("token").append(requestDTO.getToken()).
                append("v").append(requestDTO.getV()).append(JddjConsts.APP_SECRET);

        String sign = DigestUtils.md5Hex(sbSignContent.toString()).toUpperCase();

        log.info("【{}】生成签名【{}】【{}】",JddjConsts.CHANNEL_NAME, sbSignContent.toString(),sign);
        return sign;
    }

    /**
     * 验证签名
     *
     * @param requestDTO
     * @return
     */
    public static boolean verifySign(JddjRequestDTO requestDTO) {

        if (Objects.isNull(requestDTO) || StringUtil.isBlank(requestDTO.getSign())) {
            return false;
        }

        String sign = makeSign(requestDTO);

        return requestDTO.getSign().compareToIgnoreCase(sign) == 0 ? true : false;
    }

    /**
     * 发送 http 请求
     *
     * @param path
     * @param requestDTO
     * @return
     */
    public static String postRequest(String path, JddjRequestDTO requestDTO) {

        // 参数判断
        if (StringUtil.isBlank(path) || Objects.isNull(requestDTO)) {
            log.info("【{}】发送请求失败，参数不能为空",JddjConsts.CHANNEL_NAME);
            return "";
        }

        // 生成请求的参数
        String postUrl = JddjConsts.API_URL + path;
        Map<String,String> params = getRequestParam(requestDTO);

        log.info("【{}】发送请求，URL【{}】,参数【{}】",JddjConsts.CHANNEL_NAME,postUrl,params.toString());

        String response = "";
        for (int i=0; i<3; i++) {
            try {
                if (postUrl.matches("https(.*)")) {
                    response = HttpUtil.httpsPost(postUrl, params);
                } else {
                    response = HttpUtil.httpPost(postUrl, params);
                }

                if (StringUtil.isNotBlank(response)) {
                    break;
                }
            } catch (Exception exception) {
                log.info("【{}】发送请求失败,{}",JddjConsts.CHANNEL_NAME,Objects.nonNull(exception)? exception.getMessage():"网络请求异常");
            }
        }

        log.info("【{}】发送请求应答【{}】",JddjConsts.CHANNEL_NAME,response);
        return response;
    }
}
